package fanketly.core.lib.base.utils.assist

import android.app.Activity
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout

/**
 *Create by Fanketly on 2022/7/3
 *Gitee:https://gitee.com/fanketly
 *desc:
 */
class BaseContentAssist {
    // 最外层 Layout
    @JvmField
    var rootLinear: LinearLayout? = null

    fun bind(activity: Activity): BaseContentAssist {
        rootLinear = LinearLayout(activity)
        rootLinear?.orientation = LinearLayout.VERTICAL
        rootLinear?.layoutParams = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.MATCH_PARENT
        )
        return this
    }

    /**
     * contentLinear 添加 View
     * @return [DevBaseContentAssist]
     */
    fun addContentView(
        view: View?,
        params: ViewGroup.LayoutParams?
    ): BaseContentAssist {
        return addView(rootLinear, view, -1, params)
    }

    /**
     * contentLinear 添加 View
     * @return [DevBaseContentAssist]
     */
    fun addContentView(
        view: View?,
        index: Int
    ): BaseContentAssist {
        return addView(rootLinear, view, index)
    }

    /**
     * 添加 View
     * @param viewGroup 容器 Layout
     * @param view      待添加 View
     * @param index     添加索引
     * @param params    LayoutParams
     * @return [DevBaseContentAssist]
     */
    private fun addView(
        viewGroup: ViewGroup?,
        view: View?,
        index: Int,
        params: ViewGroup.LayoutParams? = null
    ): BaseContentAssist {
        // ViewUtils.removeSelfFromParent(view)
        val parent = view?.parent as? ViewGroup
        // 防止重复添加, 当 parent 不为 null 则表示已添加, 则进行移除
        parent?.removeView(view)
        view?.let {
            if (params != null)
                viewGroup?.addView(it, index, params)
            else
                viewGroup?.addView(it, index)
        }
        return this
    }

}